

import time
import dht
import network

from machine import Pin,Timer,RTC
from mqtt import MQTTClient
from gc import mem_free


def connect_wifi(ssid, passwd):
    global wlan
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True) 
    wlan.disconnect()
    wlan.connect(ssid, passwd)
    while (wlan.ifconfig()[0] == '0.0.0.0'):
        time.sleep(1)
    wlan_info = wlan.ifconfig()

    print("连接的Wifi信息:")
    print("IP地址:" + wlan_info[0])
    print("子网掩码: " + wlan_info[1])
    print("网关:" + wlan_info[2])
    print("DNS:" + wlan_info[3])

def sub_callback(topic, msg):
    print(">>> 接收到数据", (topic, msg))


mqtt_client = None

# MQTT参数配置

#  MQTT服务器地址
broker_address = '119.91.118.138'  
#  MQTT服务器端口
broker_port = '1883'
#  MQTT设备id   
client_id = 'ESP32-C3'   
# mqtt 设备用户名
user_name = ''
# mqtt 设备密码  
password = '' 
# 推送主题
publish_topic = 'temperature'   
# 订阅主题
subscribe_topic = 'nb'  

## 无限网络配置

# 无线网名称
SSID = '****'  
#无线网密码
PASSWORD = '****'  


def temperature():
    # 根据设置的GPIO口配置
    t_sensor = dht.DHT11(Pin(9))
    t_sensor.measure()
    temp = t_sensor.temperature()
    humi = t_sensor.humidity()
    print("{}'C  {}% ".format(temp,humi))
    return (temp, humi)

def send_temperature(mqtt_client):
    t, h = temperature()
    mqtt_client.publish(topic=publish_topic,msg="SZ_{}_{}".format(t, h))
    

if __name__ == '__main__':
    try:

        connect_wifi(SSID, PASSWORD)
        print(">>>> 当前可用内存: %s Byte" % str(mem_free()))

        mqtt_client = MQTTClient(client_id=client_id, server=broker_address, port=broker_port, user=user_name,
                                 password=password, keepalive=60)
        mqtt_client.set_callback(sub_callback)
        mqtt_client.connect()
        mqtt_client.subscribe(subscribe_topic)
        print("客户端名称: %s" % mqtt_client.client_id)
        
        t_timer = Timer(0)
        t_timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:send_temperature(mqtt_client))
        while True:
            mqtt_client.wait_msg()
    except Exception as e:
        print('exception:', e)
    finally:
        if (mqtt_client is not None):
            mqtt_client.disconnect()
        wlan.disconnect()
        wlan.active(False)


